using System.Net.Http;
using System.Web.Http;
using AutoMapper;
using Common.Commands.MemberCommands;
using Common.Views;
using Dto.ApiRequests.MemberForms;
using Dto.ApiResponses.MemberResponses;
using Sanelib.Common.Helpers;
using Sanelib.DataView;
using Sanelib.Dto;
using WebApp.Services;

namespace WebApp.ControllerApis
{
    [Authorize]
    public class MemberCardController : SmartApiController
    {
        private readonly IViewRepository<MemberView> _memberViewRepository;

        public MemberCardController(IUserSession userSession, IMappingEngine mappingEngine, IViewRepository<MemberView> memberViewRepository) : base(userSession, mappingEngine)
        {
            _memberViewRepository = memberViewRepository;
        }

        public HttpResponseMessage Get(MemberLookupForm form)
        {
            if (!string.IsNullOrEmpty(form.Code))
            {
                var view = _memberViewRepository.GetByKey(Property.Of<MemberView>(x => x.Code), form.Code);
                if (view != null) return Content(Mapper.Map<MemberView, MemberResponse>(view));
            }
            else if (!string.IsNullOrEmpty(form.TagId))
            {
                var view = _memberViewRepository.GetByKey(Property.Of<MemberView>(x => x.TagId), form.TagId);
                if (view != null) return Content(Mapper.Map<MemberView, MemberResponse>(view));
            }

            var errors = new ErrorResult();

            errors.AddError("TagId or Code", "does not match");
            return Content(errors);
        }

        public HttpResponseMessage Post(MemberCardRegisterForm form)
        {
            var member = _memberViewRepository.GetByKey(Property.Of<MemberView>(x => x.Code), form.Code);

            if (member == null)
            {
                return Content(new ErrorResult());
            }

            var command = new RegisterMemberCard
            {
                Id = member.Id,
                TagId = form.TagId
            };

            return ExecuteCommand(command);
        }
    }
}